<?php
namespace control;

/*
*生产订单跟踪表类
*/

class productTrackClass extends adIndexClass
{
    private const page = 'productTrack';
    private const title = '生产订单跟踪表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '产品名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '生产数量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'progress'          => [
                        'name'  => '生产进度',
                        'width' => 400,
                    ],
                    'notIn'          => [
                        'name'  => '未入库数量',
                        'width' => 150,
                    ],
                    'endDate'          => [
                        'name'  => '计划完工日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'lastDate'          => [
                        'name'  => '最后入库日期',
                        'width' => 150,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "产品编码"   => text(array("name" => "code")),
                    "产品名称"   => text(array("name" => "materialName")),
                ],
                [
                    '生产线'  =>  selectMultiple(["name" => "lineId", 'table' => "product_line", 'where' => "coid = '" . self::$coid . "'", 'sqlId' => 'id', 'field' => "concat(workshop,'-',name) as name,id", 'sqlField' => 'name', 'class' => 'width200']),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "计划完工日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "b.lineId" => $this->post('lineId'),
            "b.coid" => self::$coid,
            "b.state" => '已确认'
        );
        $and = '';

        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'), field: "b.recordDate");
        }
        if ($this->post('time')) {
            //单据日期
            $and .= self::timeComparison($this->post('time'), field: "b.endDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field' => "a.*,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.type,b.recordDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //已入库数量
            $in_num = 0;
            $all = find(array('table' => 'machining_in_order_detail', 'where' => "sourceId = '$array[id]'"));
            foreach ($all['array'] as $val) {
                $inventory_detail = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]'"));
                foreach ($inventory_detail['array'] as $detail) {
                    $in_num += machiningOrderClass::material_num_change($detail['materialId'], $detail['unit'], $array['unit'], $detail['num']);
                }
            }
            //总的待入库数量
            $all_in_num = 0;
            $all = find(array('table' => 'machining_in_order_detail', 'where' => "sourceId = '$array[id]'"));
            foreach ($all['array'] as $val) {
                $inventory_detail = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]'"));
                foreach ($inventory_detail['array'] as $detail) {
                    $all_in_num += machiningOrderClass::material_num_change($detail['materialId'], $detail['unit'], $array['unit'], $detail['orderNum']);
                }
            }
            $state = '待入库';
            if ($all_in_num > $in_num && $in_num > 0) {
                $state = '部分入库';
            } elseif ($in_num == $all_in_num && $in_num > 0) {
                $state = '已入库';
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $product_line = query('product_line', "id = '$array[lineId]'");
                        $row[] = $product_line['workshop'] . '-' . $product_line['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'progress':
                        $row[] = $this->progress($array['routingId'], $array['id']);
                        break;
                    case 'notIn':
                        $row[] = $array['num'] - $in_num;
                        break;
                    case 'lastDate':
                        //最后入库日期
                        $last = find(array(
                            'table' => 'inventory_detail as a join inventory as b on a.orderId = b.id',
                            'field' => "b.confirmTime as lastDate",
                            'single' => "a.sourceId in (select id from machining_in_order_detail where sourceId = '$array[id]') order by b.confirmTime desc"
                        ));
                        $row[] = isset($last['lastDate']) && $state != '待入库' ? $last['lastDate'] : '';
                        break;
                    case 'state':
                        $row[] = $state;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        $inventory = find(array(
            'table'  => ' machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId join machining_in_order_detail as miod on miod.sourceId = a.id join inventory_detail as mx on mx.sourceId = miod.id ',
            'single'=>$where,
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notIn'        => self::formattingFigure($totalQuery['num'] - $inventory['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "liHeight" => 80,
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $this->style() . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 生产进度
     */
    public function progress($routingId, $machiningOrderMxId): string
    {
//        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
        if (self::total(['table'=>'machining_card','where'=>"sourceMxId = '$machiningOrderMxId'"]) >0) {
            return $this->machiningCard($routingId, $machiningOrderMxId);
        } elseif(self::total(['table'=>'machining_send_order','where'=>"machiningOrderMxId = '$machiningOrderMxId'"]) >0) {
            $routing_detail = find(array('table' => 'routing_detail', 'where' => "orderId = '$routingId' order by list asc"));
            $temp = '';
            $stateBox = [];
            foreach ($routing_detail['array'] as $index => $array) {
                $process = query('process', "id = '$array[processId]'");
                //派工数量
                $sendOrderNum = find(array(
                    'table' => 'machining_send_order',
                    'where' => "machiningOrderMxId = '$machiningOrderMxId' and processId = '$array[processId]' and state = '已确认'",
                    'sum' => "num"
                ));
                //报工合格数量
                $reportNum = find(array(
                    'table' => 'process_report',
                    'single' => "sendId in (select id from machining_send_order where machiningOrderMxId = '$machiningOrderMxId' and state = '已确认') and processId = '$array[processId]' and state = '已确认'", 'field' => "ifnull(sum(yield-badNum),0) as total"
                ))['total'];
                $reportNum = self::formattingFigure($reportNum, 'numPrecision');
                $stateClass = '';
                $rate = '0%';
                if ($sendOrderNum > 0) {
                    if (self::formattingFigure($reportNum, 'numPrecision') >= self::formattingFigure($sendOrderNum, 'numPrecision')) {
                        $rate = '完成';
                        $stateClass = 'complete';
                    } else {
                        $rate = floor(($reportNum / $sendOrderNum) * 100) . '%';
                        $stateClass = in_array('progress-now', $stateBox) ? '' : 'progress-now';
                    }
                }
                $stateBox[] = $stateClass;
                if ($index > 0) {
                    $divClass = match ($stateClass) {
                        'complete' => 'green',
                        'progress-now' => 'blue',
                        default => '',
                    };
                    $temp .= <<<eof
 <div class="divder $divClass"></div>
eof;
                }
                $temp .= <<<eof
 <div><div title="派工数量：{$sendOrderNum}，报工合格数量：{$reportNum}" class="progress-li $stateClass">{$rate}</div><div>{$process['name']}</div></div>
eof;
            }

            return <<<eof
<div class="progress-ul">
   $temp
</div>
eof;
        }
        return '';
    }

    /**
     * 生产流转卡进度
     */
    public function machiningCard($routingId, $machiningOrderMxId): string
    {
        $html = '';
        $stateBox = [];
        $all = find([
            'table' => 'machining_card as a join machining_card_detail as b on a.id = b.orderId',
            'field' => "b.*,a.num",
            'where' => "a.sourceMxId = '$machiningOrderMxId' and a.routingId = '$routingId' order by b.list asc"
        ]);
        foreach ($all['array'] as $index => $array) {
            $process = query('process', "id = '$array[processId]'");
            //报工合格数量
            $reportNum = find(array(
                'table' => 'process_report',
                'single' => "sendId ='$array[id]' and processId = '$array[processId]' and state = '已确认'",
                'field' => "ifnull(sum(yield-badNum),0) as total"
            ))['total'];
            $reportNum = self::formattingFigure($reportNum, 'numPrecision');
            if (self::formattingFigure($reportNum, 'numPrecision') >= self::formattingFigure($array['num'], 'numPrecision')) {
                $rate = '完成';
                $stateClass = 'complete';
            } else {
                $rate = floor(($reportNum / $array['num']) * 100) . '%';
                $stateClass = in_array('progress-now', $stateBox) ? '' : 'progress-now';
            }
            $stateBox[] = $stateClass;
            if ($index > 0) {
                $divClass = match ($stateClass) {
                    'complete' => 'green',
                    'progress-now' => 'blue',
                    default => '',
                };
                $html .= <<<eof
 <div class="divder $divClass"></div>
eof;
            }
            $array['num'] = self::formattingFigure($array['num'], 'numPrecision');
            $html .= <<<eof
 <div><div title="计划数量：{$array['num']}，报工合格数量：{$reportNum}" class="progress-li $stateClass">{$rate}</div><div>{$process['name']}</div></div>
eof;
        }
        return <<<eof
<div class="progress-ul">
   $html
</div>
eof;
    }

    public
    function style()
    {
        return <<<eof
<style>
.divder{width: 20px;height: 1px;background-color: #c3c3c3;margin: -22px 5px 0 5px;}
.progress-ul{display: flex;flex-direction: row;align-items: center;}
.progress-ul>div{text-align: center;font-size: 12px}
.progress-li{width: 25px;height: 25px;line-height: 25px;padding: 5px;border-radius: 50%;border: 1px solid #c3c3c3;margin: 0 auto}
.complete{color: #00B83F;border-color: #00B83F}
.progress-now{color: #629afd;border-color: #629afd}
.blue{background-color: #629afd}
.green{background-color: #00B83F}


</style>
eof;

    }

    /**
     * 导出
     */
    public
    function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field' => "a.*,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.type,b.recordDate",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by b.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                //已入库数量
                $in_num = 0;
                $all = find(array('table' => 'machining_in_order_detail', 'where' => "sourceId = '$array[id]'"));
                foreach ($all['array'] as $val) {
                    $inventory_detail = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]'"));
                    foreach ($inventory_detail['array'] as $detail) {
                        $in_num += machiningOrderClass::material_num_change($detail['materialId'], $detail['unit'], $array['unit'], $detail['num']);
                    }
                }
                //总的待入库数量
                $all_in_num = 0;
                $all = find(array('table' => 'machining_in_order_detail', 'where' => "sourceId = '$array[id]'"));
                foreach ($all['array'] as $val) {
                    $inventory_detail = find(array('table' => 'inventory_detail', 'where' => "sourceId = '$val[id]'"));
                    foreach ($inventory_detail['array'] as $detail) {
                        $all_in_num += machiningOrderClass::material_num_change($detail['materialId'], $detail['unit'], $array['unit'], $detail['orderNum']);
                    }
                }
                $state = '待入库';
                if ($all_in_num > $in_num && $in_num > 0) {
                    $state = '部分入库';
                } elseif ($in_num == $all_in_num) {
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table' => 'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field' => "b.orderDate as lastDate",
                    'single' => "a.sourceId in (select id from machining_in_order_detail where sourceId = '$array[id]')"
                ));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '生产线'=>productLineClass::getName($array['lineId']),
                            '产品编码'=>$array['code'],
                            '产品名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '生产数量'=>self::lostZero($array['num'], 'numPrecision'),
                            '未入库数量'=> $array['num'] - $in_num,
                            '计划完工日期'=>$array['endDate'],
                            '最后入库日期'=>isset($last['lastDate']) && $state != '待入库' ? $last['lastDate'] : '',
                            '状态'=>$state,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了生产订单跟踪表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "生产订单跟踪表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'生产数量',
                    'aliasName'=>'生产数量',
                ],
                [
                    'columnName'=>'未入库数量',
                    'aliasName'=>'未入库数量',
                ],
                [
                    'columnName'=>'计划完工日期',
                    'aliasName'=>'计划完工日期',
                ],
                [
                    'columnName'=>'最后入库日期',
                    'aliasName'=>'最后入库日期',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}

